from app import db
from datetime import datetime

# 用户模型，对应数据库中的users表
class User(db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)  # 用户ID，主键
    username = db.Column(db.String(50), unique=True, nullable=False)  # 用户名，唯一且不能为空
    avatar = db.Column(db.String(255))  # 用户头像
    created_at = db.Column(db.DateTime, default=datetime.utcnow)  # 创建时间
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)  # 更新时间
    
    # 额外字段，用于认证
    email = db.Column(db.String(120), unique=True)  # 邮箱
    password = db.Column(db.String(128))  # 密码
    phone = db.Column(db.String(20))  # 用户电话
    address = db.Column(db.Text)  # 用户地址
    is_admin = db.Column(db.Boolean, default=False)  # 是否为管理员

    # 关注关系 - 用户关注的人
    following = db.relationship('User',
                                secondary='user_follows',
                                primaryjoin='User.id == user_follows.c.follower_id',
                                secondaryjoin='User.id == user_follows.c.followed_id',
                                backref='followers')

    # 将用户对象转换为字典格式，方便返回JSON
    def to_dict(self):
        return {
            'id': self.id,
            'username': self.username,
            'avatar': self.avatar,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'email': self.email,
            'phone': self.phone,
            'address': self.address,
            'is_admin': self.is_admin,
            'followers_count': len(self.followers),
            'following_count': len(self.following)
        }

# 关注关系模型，对应数据库中的user_follows表
class UserFollows(db.Model):
    __tablename__ = 'user_follows'
    
    id = db.Column(db.Integer, primary_key=True)  # 自增ID
    follower_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)  # 粉丝ID
    followed_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)  # 被关注人ID
    created_at = db.Column(db.DateTime, default=datetime.utcnow)  # 关注时间
    
    # 设置联合唯一索引，确保一个用户不能重复关注另一个用户
    __table_args__ = (db.UniqueConstraint('follower_id', 'followed_id', name='unique_follow'),)

    # 将关注关系对象转换为字典格式
    def to_dict(self):
        return {
            'id': self.id,
            'follower_id': self.follower_id,
            'followed_id': self.followed_id,
            'created_at': self.created_at.isoformat()
        }